package com.gmlive.common.imageloader.url

import android.net.Uri
import com.gmlive.common.imageloader.ImageLoader
import com.gmlive.common.imageloader.dip2px
import com.gmlive.common.imageloader.request.RequestCreate
import java.io.UnsupportedEncodingException
import java.net.URLEncoder

/**
 *  Create by: fanfeiyue
 *  on: 2019-11-22
 *  desc:
 */
class UrlCreate(url: String) {

    companion object {
        const val ORIGIN_ORIGIN = 1 // 原图
        const val ORIGIN_SCALE = 0 // 裁剪缩放
        const val QUALITY_DEFAULT = 80
    }

    private val data = UrlBuilder(url)

    fun setWidthPx(widthPx: Int): UrlCreate {
        data.width = widthPx
        return this
    }

    fun setHeightPx(heightPx: Int): UrlCreate {
        data.height = heightPx
        return this
    }

    fun setWidthDp(widthDp: Int): UrlCreate {
        data.width = widthDp.dip2px()
        return this
    }

    fun setHeightDp(heightDp: Int): UrlCreate {

        data.height = heightDp.dip2px()
        return this
    }

    fun setQuality(quality: Int): UrlCreate {
        data.quality = quality
        return this
    }

    fun setOrigin(origin: Int): UrlCreate {
        data.origin = origin
        return this
    }

    fun setWebpEnable(enable: Boolean?): UrlCreate {
        val enableInt = if (enable == true) 1 else 0
        data.webpEnable = enableInt
        return this
    }

    fun get(): RequestCreate {
        var newUrl = data.takeIf { it.height == null && it.width == null && it.origin == null && it.quality == null }?.url
        try {
            newUrl = newUrl ?: "${getImageScaleUrl()}c=0" +
                    data.width.toStringWithParam("w") +
                    data.height.toStringWithParam("h") +
                    data.quality.toStringWithParam("s") +
                    data.origin.toStringWithParam("o") +
                    data.webpEnable.toStringWithParam("t") +
                    "&url=${URLEncoder.encode(data.url, "UTF-8")}"

        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
        return RequestCreate(Uri.parse(newUrl))
    }

    fun getCircleImage(): RequestCreate {
        val newUrl: String = data.url.let { url ->
            try {
                "${getImageScaleUrl()}w=400&h=400&s=100&t=4&url=${URLEncoder.encode(url, "UTF-8")}"
            } catch (e: UnsupportedEncodingException) {
                e.printStackTrace()
                url
            }
        }
        return RequestCreate(Uri.parse(newUrl))
    }

    private fun getImageScaleUrl(): String {
        return ImageLoader.IMAGE_SCALE_URL
                ?: "https://imagescalekyik.hnyapu.cn/imageproxy2/dimgm/scaleImage?"
    }

    private fun Int?.toStringWithParam(param: String): String {
        return if (this == null) "" else "&$param=${this}"
    }

}